package cn.ittgh.controller.Map;

import cn.hutool.core.map.MapUtil;
import cn.ittgh.pojo.Commons.Result;
import cn.ittgh.pojo.TencentMap.Constant.TencentMapConstant;
import cn.ittgh.pojo.TencentMap.TencentMapResult;
import cn.ittgh.utils.Tencent.TencentMD5Util;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/map")
public class MapController {
	@Autowired
	private RestTemplate restTemplate;

	@GetMapping("/placeSearch")
	public Result placeSearch(
			@RequestParam @NotNull String keyword,
			@RequestParam @NotNull String lat,
			@RequestParam @NotNull String lng,
			@RequestParam @NotNull int radius
	) {
		int autoExtend = 1;
		Map<String, String> params = MapUtil.builder(new HashMap<String, String>())
				.put("key", TencentMapConstant.KEY)
				.put("boundary", "nearby(" + lat + "," + lng + "," + radius + "," + autoExtend + ")")
				.put("keyword", keyword)
				.put("orderby", "_distance")
				.build();
		// 签名
		String signature = TencentMD5Util.generateSignatureGet(TencentMapConstant.PLACE_SEARCH, params);
		String url = TencentMapConstant.ADDRESS + TencentMapConstant.PLACE_SEARCH + "?" + TencentMD5Util.encodeParams(params) + "sig=" + signature;

		RestTemplate restTemplate = new RestTemplate();
		TencentMapResult result = restTemplate.getForObject(url, TencentMapResult.class);

		if (result.getStatus() != 0) {
			return Result.error(result.getMessage());
		} else {
			return Result.success(result);
		}
	}

	@GetMapping("/bicyclingLine")
	public Result getDrivingLine(
			@RequestParam @NotNull String from,
			@RequestParam @NotNull String to
	) {
		Map<String, String> params = MapUtil.builder(new HashMap<String, String>())
				.put("key", TencentMapConstant.KEY)
				.put("from", from)
				.put("to", to)
				.build();
		// 签名
		String signature = TencentMD5Util.generateSignatureGet(TencentMapConstant.BICYCLING, params);
		String url = TencentMapConstant.ADDRESS + TencentMapConstant.BICYCLING + "?" + TencentMD5Util.encodeParams(params) + "sig=" + signature;

		RestTemplate restTemplate = new RestTemplate();
		TencentMapResult result = restTemplate.getForObject(url, TencentMapResult.class);
		if (result.getStatus() != 0) {
			return Result.error(result.getMessage());
		} else {
			return Result.success(result);
		}
	}
	/**********HTTP POST method**************/
//	@PostMapping(value = "/testPost")
//	public void postJson(@RequestBody JSONObject param) {
//		System.out.println(param.toJSONString());
//		param.put("action", "post");
//		param.put("username", "tester");
//		param.put("pwd", "123456748");
//		System.out.println(param);
//	}
}
